package com.cooper.controllers.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.entity.FunctionInfo;
import com.cooper.entity.UserInfo;
import com.cooper.service.admin.FunctionService;
import com.cooper.util.Controllers;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.rest.Get;

public class SidebarController {
	
	@Autowired
	private FunctionService functionService;
	
	@Get
	public String execute(Invocation inv) throws Exception{
		UserInfo user = Controllers.getUserInfo(inv);
		if(null == user){
			return "@";
		}
		
		List<FunctionInfo> functionList = this.functionService.getAllFunctionList();
		
		StringBuffer strTree = generateMenuTree(functionList);
		inv.getRequest().getSession().setAttribute("menuTree", strTree);
		return "@" + strTree.toString();
	}
	
	/**
	 * 根据菜单List生成HTML树
	 * @param functionList
	 * @return
	 * @date Nov 17, 2011 11:36:22 AM
	 * @author tianlg
	 */
	public static StringBuffer generateMenuTree(List<FunctionInfo> functionList){
		StringBuffer buffer = new StringBuffer();
		buffer.append("<ul class='tree'>");
		FunctionInfo lastInfo = null;
		int closeCount = 0;
		for(int index=0,len=functionList.size(); index < len; index ++){
			FunctionInfo info = functionList.get(index);
			if(0 < index){
				if(info.getParentId().equals(lastInfo.getParentId())){//与上一个菜单同归属
					if(true == lastInfo.isHasChild()){
						buffer.append("</ul></li>\n");
						closeCount--;
					}
				}else if(info.getParentId().equals(lastInfo.getFunctionId())){//为上一个菜单的子节点
					
				}else{
					String queueIndex = info.getQueueIndex();
					String lastQueueIndex = lastInfo.getQueueIndex();
					String startIndex = queueIndex.length()<lastQueueIndex.length()?queueIndex: lastQueueIndex;
					int start = 2;
					int level = closeCount;
					while(start < startIndex.length()){
						if(queueIndex.substring(0, start).equals(lastQueueIndex.subSequence(0, start))){
							start +=2;
							level--;
						}else{
							break;
						}
					}
					for(int i=0;i<level;i++){
						buffer.append("</ul></li>\n");
						closeCount --;
					}
				}
			}
			if(true == info.isHasChild()){
				buffer.append("<li><span class='").append(closeCount<1?"fold1":"fold2").append("'>")
					.append(info.getFunctionName()).append("</span><ul>");
				closeCount ++;
			}else{
				buffer.append("<li><span class='file'><a href='")
					.append(info.getUrl()).append("' id='").append(info.getFunctionId()).append("'>")
					.append(info.getFunctionName()).append("</a></span></li>\n");
			}
			lastInfo = info;
		}
		for(int i=0,n=closeCount;i<n;i++){
			buffer.append("</ul></li>\n");
		}
		buffer.append("</ul>");
		return buffer;
	}

}
